package com.ferry.id.pool.dao;
import	java.util.HashMap;

import com.ferry.id.pool.domain.Alloc;
import org.apache.ibatis.mapping.Environment;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.ibatis.transaction.TransactionFactory;
import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;

import javax.sql.DataSource;
import java.util.List;
import java.util.Map;

public class AllocDaoImpl implements AllocDao {

    private SqlSessionFactory sqlSessionFactory;

    public AllocDaoImpl(DataSource dataSource) {
        TransactionFactory transactionFactory = new JdbcTransactionFactory();
        Environment environment = new Environment("development", transactionFactory, dataSource);
        Configuration configuration = new Configuration(environment);
        configuration.addMapper(AllocMapper.class);
        sqlSessionFactory = new SqlSessionFactoryBuilder().build(configuration);
    }

    @Override
    public List<Alloc> getAllAllocs() {
        SqlSession sqlSession = sqlSessionFactory.openSession(false);
        try {
            return sqlSession.selectList("com.ferry.id.pool.dao.AllocMapper.getAllAllocs");
        } finally {
            sqlSession.close();
        }
    }

    @Override
    public Alloc updateMaxIdAndGetAlloc(String namespace) {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        try {
            Map<String, Object> param = new HashMap<String, Object> ();
            param.put("namespace", namespace);
            param.put("updateTime", System.currentTimeMillis());
            sqlSession.update("com.ferry.id.pool.dao.AllocMapper.updateMaxId", param);
            Alloc result = sqlSession.selectOne("com.ferry.id.pool.dao.AllocMapper.getAlloc", namespace);
            sqlSession.commit();
            return result;
        } finally {
            sqlSession.close();
        }
    }

    @Override
    public Alloc updateMaxIdByCustomStepAndGetLeafAlloc(Alloc alloc) {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        try {
            sqlSession.update("com.ferry.id.pool.dao.AllocMapper.updateMaxIdByCustomStep", alloc);
            Alloc result = sqlSession.selectOne("com.ferry.id.pool.dao.AllocMapper.getAlloc", alloc.getNamespace());
            sqlSession.commit();
            return result;
        } finally {
            sqlSession.close();
        }
    }

    @Override
    public List<String> getAllNamespaces() {
        SqlSession sqlSession = sqlSessionFactory.openSession(false);
        try {
            return sqlSession.selectList("com.ferry.id.pool.dao.AllocMapper.getAllNamespaces");
        } finally {
            sqlSession.close();
        }
    }
}
